public with sharing class OpportunityManager {
	
	/**
	* <P> This method is used to create Assets for the given opportunities.</P>
	* @param : opportunities as a List of Opportunity
	*
	*/
	public void createAssetsForOpportunities(Set<Id> opportunitiesIds){
		
		AssetManager assetManager = null;
		List <Database.SaveResult> saveResult=null;
		Boolean updateOLIs=false;
			
		if(null!= opportunitiesIds && !opportunitiesIds.isEmpty()){
			assetManager= new AssetManager();
		List<OpportunityLineItem> opportunityLineItems=getOLIWithPricebookEntryForOpportunities(opportunitiesIds);
		
		
		saveResult = assetManager.createAssetsForOpportunityLineItems(opportunityLineItems);
		
		//Updating OLIs with Asset reference
		if(null!= saveResult && !saveResult.isEmpty()){
			for (Integer itr=0 ; itr<saveResult.size(); itr++){
				
				if(null!= opportunityLineItems && null !=opportunityLineItems.get(itr) && saveResult.get(itr).isSuccess()){
					updateOLIs=true;
					opportunityLineItems.get(itr).Asset__c=saveResult.get(itr).getId();
				}
			}
		}
		
		
		 if(updateOLIs){
		 	update opportunityLineItems;
		 }
		}
		
	}
	
	

/**
	* <P> This method is used to Delete the Assets for the given opportunities.</P>
	* @param : opportunities as a List of Opportunity
	*
	*/
	public void deleteAssetsForOpportunities(Set<Id> opportunities){
		
		Boolean updateOLIs=false;
		AssetManager assetManager = null;
			
		if(null!= opportunities && !opportunities.isEmpty()){
			updateOLIOfOpportunitiesOnAssetRemoval(opportunities);
			assetManager= new AssetManager();
			
			List<Database.Deleteresult> result=assetManager.deleteAssetsForOpportunities(opportunities);
			
		}
	}
	
	public List<OpportunityLineItem> getOLIWithPricebookEntryForOpportunities(Set<Id> opportunities){
		
		List<OpportunityLineItem> opportunityLineItems=null;
		if(null!= opportunities && !opportunities.isEmpty()){
			
		
			opportunityLineItems= [SELECT
					 OLI.id, OLI.Description,	OLI.Quantity, OLI.ServiceDate,OLI.TotalPrice,
					 OLI.Opportunity.AccountId,OLI.Opportunity.CloseDate, 
					 PriceBookEntry.Product2Id, PricebookEntry.ProductCode,
					 PricebookEntry.product2.Name
				From
	 				OpportunityLineItem OLI  where OLI.Asset__c = '' AND oli.OpportunityId in :opportunities];
			
			
			
		}
	 return opportunityLineItems;
	}
	
	public set<Id> getIdsOfSForSObjectList(List<Sobject> sOjects){
		
		Set<Id> ids= null;
		if(null != sOjects && !sOjects.isEmpty()){
			ids = new Set<Id>();
			for (Sobject sOject : sOjects){
				
				if ( null!= sOject){
				ids.add(sOject.id);
				}
			}
		}
		return ids;
	}
	
	
	public void updateOLIOfOpportunitiesOnAssetRemoval(Set<Id> opportunities){
		
		List<OpportunityLineItem> opportunityLineItems=[SELECT OLI.ID from OpportunityLineItem OLI where OLI.Asset__c = '' AND oli.OpportunityId in :opportunities];
		for(OpportunityLineItem oli : opportunityLineItems){
			
			oli.Asset__c=null;
			
		}
		update opportunityLineItems;
		
		
	}
}